# -*- coding: utf-8 -*-
# @Time    : 2024/1/23  13:03
# @Author  : zhanghao
# @FileName: slaver.py
# @Software: PyCharm
"""
    Description: 用于将识别结果返回给yiweb
"""
import json
from threading import Thread
from config.logger import Logger
from db.sqlite import Sqlite
from api.domain.file_result import FileResult
from api.response.task_response import TaskResponse

import time
import datetime
import requests


class Slaver(Thread):
    url = 'http://anbao2.yiweb.com/api/ocr/getLists'

    logger = Logger.get()

    sqlite: Sqlite

    def __init__(self, url):
        super().__init__()
        self.sqlite = Sqlite()
        self.url = url

    def run(self) -> None:
        while True:
            try:
                # 查询10个执行完成的任务，发送结果
                task_data = self.sqlite.queryCompleteTask()
                for task in task_data:
                    file_task = FileResult.build(task[0], task[1], task[2], task[3], task[4], task[5],
                                                 task[6], task[7], task[8], task[9])

                    self.logger.info('开始发送结果，文件id：' + str(file_task.id))
                    retry_times = file_task.fetchInfo('retry_time')
                    if retry_times:
                        times = int(retry_times) + 1
                    else:
                        times = 1

                    # 发送识别结果
                    task_response = TaskResponse.buildSuccess()
                    task_response.setData(file_task)
                    response = requests.post(url=self.url, json=task_response.model_dump())

                    self.logger.info(response.status_code)
                    self.logger.info(response.text)
                    if response.status_code == 200:
                        response_json = json.loads(response.content)
                        if response_json['message'] == 'SUCCESS':
                            file_task.res_send = 1
                            file_task.appendInfo('retry_time', str(times))
                            file_task.appendInfo('send_time', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                            self.sqlite.updateTask(file_task)
                        else:
                            if times > 5:
                                file_task.res_send = 3

                            file_task.appendInfo('retry_time', str(times))
                            file_task.appendInfo('send_time', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                            self.sqlite.updateTask(file_task)

                        self.logger.info('发送成功，文件id：' + str(file_task.id))
                    else:
                        if times > 5:
                            file_task.res_send = 3

                        file_task.appendInfo('retry_time', str(times))
                        file_task.appendInfo('send_time', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                        self.sqlite.updateTask(file_task)

                        self.logger.info('发送失败，文件id：' + str(file_task.id))

            except Exception as e:
                self.logger.exception('未知异常：', e)

            finally:
                time.sleep(10)
